import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { SentMessageFormEmbedComponent } from 'src/app/message/sent-message-form-embed/sent-message-form-embed.component';
import { MemberProfileVo } from 'src/app/model/member-profile-vo';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberService } from 'src/app/services/member.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styles: [``]
})
/**
 * 公共会员主页
 * @constructor
 */
export class HomeComponent implements OnInit {
  public profile: MemberProfileVo | undefined;
  public mine: boolean = false;
  public errorMessage: string = '';
  //引用发送消息表单
  @ViewChild('sentMsgF', { static: false })
  public sentMsgFormCmp!: SentMessageFormEmbedComponent;

  constructor(
    private title: Title,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private memberService: MemberService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.btnNaviSharedService.active(true);//需要全局的导航
    this.activatedRoute.url.subscribe(activeUrl =>{
      const uid: number = parseInt(activeUrl[1].path??'0');
      this.queryData(uid);
    });
  }

  ngOnInit(): void {
  }

  //切换消息发送抽屉
  public toggleMessageForm(event:Event): void{
    this.sentMsgFormCmp.toggle(this.profile?.id??-1, this.profile?.nickname??'guest');
  }


  private queryData(uid: number): void{
    if(0>= uid){
      this.router.navigate(['404']);
    }
    this.memberService.getProfile(uid).subscribe({
      next: response => {
        let mp: MemberProfileVo = response;
        if (uid !== mp.id) {
          //跳转
          this.router.navigate(['404']);
        }
        this.profile = mp;
        this.title.setTitle(this.profile.nickname + '的个人主页');
      },
      error: err => {
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            this.errorMessage = err.error.message;
          } else {
            if (err.status === 404) {
              //跳转
              this.router.navigate(['404']);
            } else {
              this.errorMessage = err.error;
            }
          }
        } else if (err instanceof Error) {
          this.errorMessage = err.message;
        } else { this.errorMessage = err; }
        //ETC
      },
      complete: () => { console.log('[Member-CTL]Completed'); }
    });
  }
}
